<template>
    <div class="pic-add" @mouseenter="showRmAction" @mouseleave="showRmAction">
        <div v-show="newViewUrl == ''">
            <div class="add-btn" :id="randomId">
            </div>
        </div>
        <div v-show="newViewUrl" class="webuploader-base" @mouseenter="showPicAction" @mouseleave="showPicAction">
            <div class="text-center">
                <img width="100%" height="100px" v-show="accept=='image' && newViewUrl" :src="newViewUrl">
            </div>
            <transition name="fade" mode="out-in">
                <div class="webuploader-action" v-show="actionStatus">
                    <span @click="edit">编辑</span>
                    <span @click="deleteImage">删除</span>
                </div>
            </transition>
        </div>
        <transition name="fade" mode="out-in">
            <div class="webuploader-close" v-show="removeStatus">
                <span class="glyphicon glyphicon-remove" @click="delComponent"></span>
            </div>
        </transition>
    </div>
</template>
<script>
    /**
     * 使用方法
     * <webuploader-single :view-url.sync="materialCurData.view_url" ref="uploadViewUrl" btn-text="选择图片"></webuploader-single>
     */
    //参考网址：http://www.mshady.com/archives/387
    export default {
        name: 'WebuploaderApplyCustom',
        props: {
            accept: {
                type: String,
                default: 'image',
            },
            viewUrl:{
                type: String,
                default:'',
            },
            link: {
                type: String,
                default: '',
            },
            disabled:{
                type: Boolean,
                default:false,
            },
            btnText:{
                type: String,
                default:'上传',
            },
            // 上传地址
            uploaderUrl: {
                type: String,
                default: '/Admin/SysFile/webUpload',
            },
            staticPath: {
                type: String,
                default: '/vendor/webuploader/'
            },
            // 上传最大数量 默认为100
            fileNumLimit: {
                type: Number,
                default: 100,
            },
            // 大小限制 默认2M
            fileSingleSizeLimit: {
                type: Number,
                default: 1024 * 1024 * 50,
            },
            // 上传时传给后端的参数，一般为token，key等
            formData: {
                type: Object,
                default: null
            },
        },
        data() {
            return {
                randomId: 'webuploader_' + new Date().getTime() + parseInt(Math.random()*(100-1))+1,
                scriptTagStatus: 0,
                uploadStatus: false,
                removeStatus: false,
                actionStatus: false,
                box: '',
                uploader: null,
                loadBox: null,
                // newViewUrl: '',
                newViewUrl: _.cloneDeep(this.viewUrl),
            };
        },
        mounted() {
            this.initUploader();
        },
        methods: {
            edit() {
                this.$emit('edit');
            },
            del() {
                this.$emit('del');
            },
            delComponent() {
                this.$emit('rm');
            },
            deleteImage() {
                let that = this;
                layer.confirm('确定删除该图片吗 ？', { icon: 3, title: '删除图片'}, function (index) {

                    that.uploadStatus = false;
                    that.newViewUrl = '';
                    that.$emit('update:url', that.newViewUrl);
                    layer.close(index);
                })
            },
            showRmAction() {
              this.removeStatus = !this.removeStatus;
            },
            showPicAction() {
                this.actionStatus = !this.actionStatus;
            },
            initUploader() {
                this.uploader = WebUploader.create({
                    auto: true, // 选完文件后，是否自动上传
                    swf: this.staticPath + 'Uploader.swf',  // swf文件路径
                    server: this.uploaderUrl,  // 文件接收服务端
                    pick: {
                        id: '#' + this.randomId,     // 选择文件的按钮
                        name: "file",
                        multiple: false,   // 是否多文件上传 默认false
                        label: this.btnText,
                    },
                    accept: this.getAccept(this.accept),  // 允许选择文件格式。
                    fileNumLimit: this.fileNumLimit, // 限制上传个数
                    //fileSingleSizeLimit: this.fileSingleSizeLimit, // 限制单个上传图片的大小
                    formData: this.formData,  // 上传所需参数
                    //设置文件上传域的name
                    fileVal: 'file',
                    duplicate: true,//是否可重复选择同一文件
                    resize: false,
                    compress: null,//图片不压缩
                    chunked: true,//分片处理
                    fileSingleSizeLimit: 1024 * 1024 * 50,//验证单个文件大小是否超出限制,50M
                    chunkSize: 1 * 1000 * 1000, //每片1M
                    chunkRetry: 2,//如果失败，重试2次
                    threads: 1,//上传并发数。允许同时最大上传进程数。
                    runtimeOrder: 'flash,html5',
                    // 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候，把图片打开。
                    disableGlobalDnd: true
                });
                this.uploader.on('uploadBeforeSend', (block, data, headers) => {
                    data.fileType = this.accept;
                    //头部成熟
                    let token = document.head.querySelector('meta[name="csrf-token"]');
                    headers['X-CSRF-TOKEN'] = token.content;
                });
                // 当有文件被添加进队列的时候，添加到页面预览
                this.uploader.on('fileQueued', (file) => {
                    this.$emit('fileChange', file);
                });

                this.uploader.on('uploadStart', (file) => {
                    // 在这里可以准备好formData的数据
                    //this.uploader.options.formData.key = this.keyGenerator(file);
                });

                // 文件上传过程中创建进度条实时显示。
                this.uploader.on('uploadProgress', (file, percentage) => {
                    this.loadBox = layer.load(1, {
                        shade: [0.3, '#fff'] //0.1透明度的白色背景
                    });
                    this.$emit('progress', file, percentage);
                });

                this.uploader.on('uploadSuccess', (file, response) => {
                    if (response.status == 'success' && _.isEmpty(response.data) == false){
                        this.newViewUrl = response.data.view_url;
                        this.uploadStatus = true;
                        this.$emit('update:url', this.newViewUrl);
                    }else{
                        utils.showToastr({'status':'error','title':'上传失败','message':response.data.msg});
                    }
                    this.$emit('success', file, response);
                });

                this.uploader.on('uploadError', (file, reason) => {
                    console.error(reason);
                    this.$emit('uploadError', file, reason);
                });

                this.uploader.on('error', (type) => {
                    let errorMessage = '';
                    if (type === 'F_EXCEED_SIZE') {
                        errorMessage = `文件大小不能超过${this.fileSingleSizeLimit / (1024 * 1000)}M`;
                    } else if (type === 'Q_EXCEED_NUM_LIMIT') {
                        errorMessage = '文件上传已达到最大上限数';
                    } else {
                        errorMessage = `上传出错！请检查后重新上传！错误代码${type}`;
                    }
                    this.$emit('error', errorMessage);
                });

                this.uploader.on('uploadComplete', (file, response) => {
                    layer.close(this.loadBox);
                    this.$emit('complete', file, response);
                });
            },
            getAccept(accept) {
                switch (accept) {
                    case 'doc':
                        return {
                            title: 'Docs',
                            extensions: 'doc,docx,ppt,pptx,pdf,txt',
                            mimeTypes: '.doc,docx,.ppt,.pptx,.pdf,.txt'
                        };
                        break;
                    case 'xls':
                        return {
                            title: 'Xls',
                            extensions: 'xls,xlsx',
                            mimeTypes: '.xls,.xlsx'
                        };
                        break;
                    case 'video':
                        return {
                            title: '视频文件',
                            extensions: 'mp4,flv,mkv,wmv',
                            mimeTypes: "video/*",
                        };
                        break;
                    case 'voice':
                        return {
                            title: '语音文件',
                            extensions: 'mp3,wma,wav,amr',
                            mimeTypes: 'audio/*'
                        };
                        break;
                    case 'image':
                        return {
                            title: 'Images',
                            extensions: 'gif,jpg,jpeg,bmp,png',
                            mimeTypes: 'image/gif,image/jpg,image/jpeg,image/bmp,image/png'
                        };
                        break;
                    default:
                        return accept
                }
            },
            refresh(){
                this.uploader.refresh();
            },
        },
    };
</script>
<style lang="scss">
    .fade-enter-active,
    .fade-leave-active {
        transition: opacity 0.1s ease;
    }

    .fade-enter,
    .fade-leave-to {
        opacity: 0;
    }
    .webuploader-base {
        width: 100%;
        height: 100%;
        position: relative;
        cursor: pointer;
    }
    .webuploader-base .webuploader-action {
        position: absolute;
        bottom: 0;
        width: 100%;
        height: 25px;
        line-height: 2;
        background: #000000;
        opacity: .5;
    }
    .webuploader-close {
        position: absolute;
        right: 2px;
        top: 0;
        color: red;
        cursor: pointer;
    }
    .webuploader-close span {
        font-size: 14px;
    }
    .webuploader-base .webuploader-action span {
        width: 50%;
        display: block;
        float: left;
        text-align: center;
        color: #ffffff;
    }
    .webuploader-container {
        position: relative;
    }
    .webuploader-element-invisible {
        position: absolute !important;
        clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
        clip: rect(1px,1px,1px,1px);
    }
    .webuploader-pick {
        position: relative;
        display: inline-block;
        cursor: pointer;
        background: #00b7ee;
        padding: 10px 15px;
        color: #fff;
        text-align: center;
        border-radius: 3px;
        overflow: hidden;
    }
    .webuploader-pick-hover {
        background: #00a2d4;
    }

    .webuploader-pick-disable {
        opacity: 0.6;
        pointer-events:none;
    }
    .webuploader-pick{
        width: 140px;
        height: 40px;
    }
</style>